package com.ysd.lis.service.inti.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.inti.IntInstrResult;
import com.ysd.lis.entity.inti.IntInstrResultLog;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.inti.IntInstrResultLogMapper;
import com.ysd.lis.mapper.inti.IntInstrResultMapper;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.request.inti.IntinstrReusltDto;
import com.ysd.lis.request.lab.IntInstrResultParam;
import com.ysd.lis.service.inti.IntInstrResultLogService;
import com.ysd.lis.service.inti.IntInstrResultService;
import com.ysd.lis.service.lab.LabChannelService;
import com.ysd.lis.service.lab.LabMaininfoService;
import com.ysd.lis.service.lab.LabRptresultService;
import com.ysd.lis.service.lab.impl.LabMainInfoServiceBakImpl;
import com.ysd.lis.service.lab.impl.LabRptresultCalcServiceImpl;
import com.ysd.lis.service.qc.QcMaterialItemResultService;
import com.ysd.lis.socket.MessageTemplate;
import com.ysd.lis.socket.WebSocketUtils;
import com.ysd.util.ToolsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Bai
 * @since 2023-12-26
 */
@Service
public class IntInstrResultServiceImpl extends ServiceImpl<IntInstrResultMapper, IntInstrResult> implements IntInstrResultService {
    @Autowired
    IntInstrResultMapper intInstrResultMapper;

    @Autowired
    IntInstrResultLogMapper intInstrResultLogMapper;
    @Autowired
    IntInstrResultLogService intInstrResultLogService;
    @Autowired
    LabRptGroupMapper labRptGroupMapper;
    @Autowired
    LabChannelMapper labChannelMapper;
    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    LabItemDictMapper labItemDictMapper;
    @Autowired
    LabRptresultService labRptresultService;
    @Autowired
    LabRptresultCalcServiceImpl labRptresultCalcService;
    @Autowired
    QcMaterialItemResultService qcMaterialItemResultService;
    @Autowired
    LabMaininfoService labMaininfoService;

    @Autowired
    LabChannelService labChannelService;


    @Override
    public Result transInstrResultsNew() {
        //从结果表中按照最新的时间查出500条数据
        Page<IntInstrResult> page = new Page<>();
        page.setCurrent(1);
        page.setSize(500);
        //Date today = new Date();
        Calendar calendar = Calendar.getInstance(); // 获取当前日期的Calendar实例
        //calendar.add(Calendar.DATE, -1); // 将日期回退一天
        Date today = calendar.getTime();
        LambdaQueryWrapper<IntInstrResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IntInstrResult::getDataType, "E")
                .and(p -> p.eq(IntInstrResult::getIsNoChannel, "N").or().isNull(IntInstrResult::getIsNoChannel))
                .isNotNull(IntInstrResult::getInstrCode)
//                .ne(IntInstrResult::getInstrCode, "")
                .ge(IntInstrResult::getCreateTime, DateUtil.beginOfDay(today).toTimestamp())
                .le(IntInstrResult::getCreateTime, DateUtil.endOfDay(today).toTimestamp())
                //.eq(IntInstrResult::getRptGroup,"BC6000")
                .orderByAsc(IntInstrResult::getCreateTime);
        Page<IntInstrResult> intInstrResultPage = intInstrResultMapper.selectPage(page, queryWrapper);
        List<IntInstrResult> intInstrResults = intInstrResultPage.getRecords();

        if (ToolsUtils.isNotEmpty(intInstrResults)) {
            //未维护通道号的数据
            List<IntInstrResult> noChannelResultList = new ArrayList<>();
            //需要删除且转移到log表中的数据
            List<IntInstrResult> delIntInstrResultList = new ArrayList<>();
            //查询报告单元
            List<String> rptGroupCodeList = intInstrResults.stream().map(IntInstrResult::getRptGroup).distinct().collect(Collectors.toList());
            LambdaQueryWrapper<LabRptGroup> queryWrapperRpt = new LambdaQueryWrapper<>();
            queryWrapperRpt.eq(LabRptGroup::getDelFlag, 0).and(wrapper -> wrapper.in(LabRptGroup::getRptGroup, rptGroupCodeList));
            List<LabRptGroup> rptGroupList = labRptGroupMapper.selectList(queryWrapperRpt);
            //按照sampleDa,prtGroup,sampleNo 分组
            Map<List<Object>, List<IntInstrResult>> intInstrResultMap = intInstrResults.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getSampleda(), s.getRptGroup(), s.getSampleNo(), s.getOrgId())));
            for (List<Object> mainInfolist : intInstrResultMap.keySet()) {
                Timestamp sampleda = null;
                String rptGroup = "";
                String sampleNo = "";
                String orgId  = "";
                if (ToolsUtils.isNotEmpty(mainInfolist.get(0))) {
                    sampleda = (Timestamp) mainInfolist.get(0);
                }
                if (ToolsUtils.isNotEmpty(mainInfolist.get(1))) {
                    rptGroup = String.valueOf(mainInfolist.get(1));
                }
                if (ToolsUtils.isNotEmpty(mainInfolist.get(2))) {
                    sampleNo = String.valueOf(mainInfolist.get(2));
                }
                if (ToolsUtils.isNotEmpty(mainInfolist.get(3))) {
                    orgId = String.valueOf(mainInfolist.get(3));
                }
                if (ToolsUtils.isNotEmpty(sampleda) && ToolsUtils.isNotEmpty(rptGroup) && ToolsUtils.isNotEmpty(sampleNo)&& ToolsUtils.isNotEmpty(orgId)) {
                    //按照分组后的数据生成labMaininfo数据
                    LabMaininfo labMaininfo = null;

                    String format = DateUtil.format(sampleda, "yyyy-MM-dd");
                    Timestamp startTime = Timestamp.valueOf(format + " 00:00:00");
                    Timestamp endTime = Timestamp.valueOf(format + " 23:59:59");

                    //优先按条码号查询
                    LambdaQueryWrapper<LabMaininfo> queryWrapper2 = new LambdaQueryWrapper<>();
                    queryWrapper2.eq(LabMaininfo::getDelFlag, 0)
                            .eq(LabMaininfo::getRptGroup, rptGroup)
                            .ge(LabMaininfo::getSampleda, startTime)
                            .le(LabMaininfo::getSampleda, endTime)
                            .eq(LabMaininfo::getReqNo, sampleNo)
                            .eq(LabMaininfo::getOrgId, orgId);
                    List<LabMaininfo> maininfoList = labMaininfoMapper.selectList(queryWrapper2);
                    if (ToolsUtils.isNotEmpty(maininfoList)) {
                        labMaininfo = maininfoList.get(0);
                    } else {
                        //标本号查询
                        LambdaQueryWrapper<LabMaininfo> queryWrapper3 = new LambdaQueryWrapper<>();
                        queryWrapper3.eq(LabMaininfo::getDelFlag, 0)
                                .eq(LabMaininfo::getRptGroup, rptGroup)
                                .ge(LabMaininfo::getSampleda, startTime)
                                .le(LabMaininfo::getSampleda, endTime)
                                .eq(LabMaininfo::getSampleNo, sampleNo)
                                .eq(LabMaininfo::getOrgId, orgId);
                        List<LabMaininfo> maininfoList1 = labMaininfoMapper.selectList(queryWrapper3);
                        if (ToolsUtils.isNotEmpty(maininfoList1)) {
                            labMaininfo = maininfoList1.get(0);
                        }
                    }
                    //无工作列表新建工作列表
                    if (null == labMaininfo) {
                        labMaininfo = new LabMaininfo();
                        labMaininfo.setRptGroup(rptGroup);
                        labMaininfo.setSampleda(startTime);
                        labMaininfo.setSampleNo(sampleNo);
                        labMaininfo.setTestTime(new Timestamp(System.currentTimeMillis()));
                        labMaininfo.setIsChk(new BigDecimal(0));
                        if(ToolsUtils.isNotEmpty(orgId)){
                            labMaininfo.setOrgId(orgId);
                        }else {
                            if(ToolsUtils.isNotEmpty(rptGroupList)){
                                labMaininfo.setOrgId(rptGroupList.get(0).getOrgId());
                            }
                        }
                        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrappers = new LambdaQueryWrapper<>();
                        lambdaQueryWrappers.eq(LabMaininfo::getSampleNo, sampleNo)
                                .eq(LabMaininfo::getRptGroup, rptGroup)
                                .eq(LabMaininfo::getSampleda, startTime)
                                .eq(LabMaininfo::getOrgId, orgId)
                                .eq(LabMaininfo::getDelFlag, 0);
                        boolean b = labMaininfoService.saveOrUpdate(labMaininfo, lambdaQueryWrappers);
                    }
                    BigDecimal isChk = labMaininfo.getIsChk();
                    if (ToolsUtils.isNotEmpty(isChk) && isChk.intValue() > 0) {
                        delIntInstrResultList.addAll(intInstrResultMap.get(mainInfolist));
                        continue;
                    }
                    //处理结果列表=======

                    //接口结果列表 //逆序
                    List<IntInstrResult> intResultList = intInstrResultMap.get(mainInfolist).stream().sorted(Comparator.comparing(IntInstrResult::getCreateTime).reversed()).collect(Collectors.toList());
                    //去重之后要更新到结果表中的数据
                    List<IntInstrResult> intInstrResultList = intResultList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(IntInstrResult::getItemNo))), ArrayList::new));

                    //去重之后需要把去重得数据找出来 放到删除并转移到log表中的集合中
                    List<IntInstrResult> quchongList = intResultList.stream().filter(item -> !intInstrResultList.contains(item)).collect(Collectors.toList());
                    if (ToolsUtils.isNotEmpty(quchongList)) {
                        delIntInstrResultList.addAll(quchongList);
                    }
                    //查出所有的通道号信息 根据报告单元，通道号集合，仪器
                    List<String> channelCodeList = intInstrResultList.stream().filter(a -> ToolsUtils.isNotEmpty(a.getItemNo())).map(IntInstrResult::getItemNo).distinct().collect(Collectors.toList());
                    //获取接口结果列表中的仪器编号
                    List<String> instrCodeList = intInstrResultList.stream().filter(a -> ToolsUtils.isNotEmpty(a.getInstrCode())).map(IntInstrResult::getInstrCode).distinct().collect(Collectors.toList());

                    MPJLambdaWrapper<LabChannel> queryWrapperChannel = new MPJLambdaWrapper<>();
                    String finalOrgId = orgId;
                    queryWrapperChannel.selectAll(LabChannel.class)
                            .innerJoin(LabItemDict.class, "rd", p -> p.eq(LabItemDict::getItemNo, LabChannel::getItemNo)
                                    .eq(LabItemDict::getRptGroup, LabChannel::getRptGroup)
                                    .eq(LabItemDict::getOrgId, finalOrgId)
                                    .eq(LabItemDict::getDelFlag, 0))
                            .eq(LabChannel::getDelFlag, 0)
                            .eq(LabChannel::getOrgId, finalOrgId)
                            .eq(LabChannel::getRptGroup, rptGroup)
                            .in(LabChannel::getChannelCode, channelCodeList)
                            .in(LabChannel::getInstrCode, instrCodeList);
                    List<LabChannel> channelList = labChannelMapper.selectList(queryWrapperChannel);
                    if (ToolsUtils.isEmpty(channelList)) {
                        //没有找到通道号 将所有的结果放入到为维护通道号得数据中去
                        for (IntInstrResult res : intResultList) {
                            res.setIsNoChannel("Y");
                            noChannelResultList.add(res);
                        }
                        continue;
                    }
                    //根据通道号查出所有的报告项目
                    List<LabItemDict> labItemDictList = null;
                    List<String> itemNoList = channelList.stream().map(LabChannel::getItemNo).distinct().collect(Collectors.toList());
                    if (ToolsUtils.isNotEmpty(itemNoList)) {
                        LambdaQueryWrapper<LabItemDict> queryWrapper1 = new LambdaQueryWrapper<>();
                        queryWrapper1.eq(LabItemDict::getDelFlag, 0)
                                .eq(LabItemDict::getRptGroup, rptGroup)
                                .eq(LabItemDict::getOrgId, orgId)
                                .in(LabItemDict::getItemNo, itemNoList);
                        labItemDictList = labItemDictMapper.selectList(queryWrapper1);
                    }
                    //查工作列表结果
                    LambdaQueryWrapper<LabRptresult> queryWrapper5 = new LambdaQueryWrapper<>();
                    queryWrapper5.eq(LabRptresult::getDelFlag, 0)
                            .eq(LabRptresult::getRptGroup, rptGroup)
                            .eq(LabRptresult::getOrgId, orgId)
                            .ge(LabRptresult::getSampleda, startTime)
                            .le(LabRptresult::getSampleda, endTime)
                            .eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
                    List<LabRptresult> rptresultList = labRptresultService.list(queryWrapper5);

                    List<LabRptresult> saveOrUpdateResultList = new ArrayList<>();
                    List<LabRptresult> updateWlResultList = new ArrayList<>();

                    for (IntInstrResult instrResult : intInstrResultList) {
                        //找通道号
                        Optional<LabChannel> first2 = channelList.stream().filter(a -> a.getChannelCode().equals(instrResult.getItemNo()) && a.getRptGroup().equals(instrResult.getRptGroup()) && a.getInstrCode().equals(instrResult.getInstrCode())).findFirst();
                        if (first2.isPresent()) {
                            LabChannel labChannel = first2.get();
                            //找到报告项目
                            Optional<LabItemDict> itemDictOptional = labItemDictList.stream().filter(a -> a.getItemNo().equals(labChannel.getItemNo()) && a.getRptGroup().equals(instrResult.getRptGroup())).findFirst();
                            if (itemDictOptional.isPresent()) {
                                LabItemDict itemDict = itemDictOptional.get();
                                LabRptresult labRptresult;
                                Optional<LabRptresult> rptresultOptional = rptresultList.stream().filter(rpt -> rpt.getItemNo().equals(labChannel.getItemNo())).findFirst();

                                if (rptresultOptional.isPresent()) {
                                    labRptresult = rptresultOptional.get();
                                } else {
                                    labRptresult = new LabRptresult();
                                    labRptresult.setMaininfoId(labMaininfo.getId());
                                    labRptresult.setSampleda(startTime);
                                    labRptresult.setRptGroup(instrResult.getRptGroup());
                                    labRptresult.setSampleNo(labMaininfo.getSampleNo());
                                    labRptresult.setItemNo(itemDict.getItemNo());
                                    labRptresult.setItemNa(itemDict.getItemNa());
                                    String resultOrgId = instrResult.getOrgId();
                                    if(ToolsUtils.isNotEmpty(resultOrgId)){
                                        labRptresult.setOrgId(resultOrgId);
                                    }else {
                                        if(ToolsUtils.isNotEmpty(rptGroupList)){
                                            labRptresult.setOrgId(rptGroupList.get(0).getOrgId());
                                        }else {
                                            if (ToolsUtils.isNotEmpty(itemDict.getOrgId())) {
                                                labRptresult.setOrgId(itemDict.getOrgId());
                                            }
                                        }
                                    }
                                }
                                labRptresult.setOd(instrResult.getOd());
                                labRptresult.setCutoff(instrResult.getCutoff());
                                labRptresult.setSco(instrResult.getSco());
                                labRptresult.setCt(instrResult.getCt());
                                labRptresult.setInstrCode(instrResult.getInstrCode());
                                //labRptresult.setInstrNa(instrResult.getInstrName());
                                labRptresult.setDisplayOrder(String.valueOf(itemDict.getSeq()));
                                labRptresult.setRawData(instrResult.getRawData());
                                if (ToolsUtils.isEmpty(labRptresult.getRawData())) {
                                    labRptresult.setRawData(instrResult.getTestResult());
                                }
                                //通过通道号得系数及差值
                                String testResult = instrResult.getTestResult();
                                String itemKind = itemDict.getItemKind();
                                if ("1".equals(itemKind)) {
                                    String adjCoefficient = labChannel.getAdjCoefficient();
                                    String adjDiffer = labChannel.getAdjDiffer();
                                    if (ToolsUtils.isNotEmpty(adjCoefficient) && ToolsUtils.isNotEmpty(adjDiffer)) {
                                        try {
                                            Double resultDouble = Double.valueOf(testResult);
                                            Double adjCoefficientDouble = Double.valueOf(adjCoefficient);
                                            Double adjDifferDouble = Double.valueOf(adjDiffer);
                                            double vResult = resultDouble * adjCoefficientDouble + adjDifferDouble;
                                            testResult = String.valueOf(vResult);
                                        } catch (Exception e) {

                                        }
                                    }
                                }
                                labRptresult.setTestResult(testResult);
                                labRptresult.setIntResultId(instrResult.getResultId());
                                labRptresult.setIsResult(1);
                                saveOrUpdateResultList.add(labRptresult);

                                if (ToolsUtils.isNotEmpty(labRptresult.getId())) {
                                    updateWlResultList.add(labRptresult);
                                }
                                //将成功插入结果表中得数据转移到log表中
                                delIntInstrResultList.add(instrResult);

                            } else {
                                //无报告项目
                            }

                        } else {
                            //无通道号
                            instrResult.setIsNoChannel("Y");
                            noChannelResultList.add(instrResult);
                        }
                    }//接口结果循环完毕

                    if (ToolsUtils.isNotEmpty(saveOrUpdateResultList)) {
                        boolean isSaveOrupdate = labRptresultService.saveOrUpdateBatch(saveOrUpdateResultList);
                        //工作列表结果
                        LambdaQueryWrapper<LabRptresult> queryWrapper6 = new LambdaQueryWrapper<>();
                        queryWrapper6.eq(LabRptresult::getDelFlag, 0)
                                .eq(LabRptresult::getRptGroup, rptGroup)
                                .eq(LabRptresult::getOrgId, orgId)
                                .ge(LabRptresult::getSampleda, startTime)
                                .le(LabRptresult::getSampleda, endTime)
                                .eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
                        List<LabRptresult> rptResultList = labRptresultService.list(queryWrapper6);
                        /*文字结果处理*/
                        LabMaininfo finalLabMaininfo = labMaininfo;

                        /*查询报告项目备用*/
                        LambdaQueryWrapper<LabItemDict> _labitemdictQuery = new LambdaQueryWrapper<>();
                        _labitemdictQuery.eq(LabItemDict::getRptGroup, labMaininfo.getRptGroup());
                        _labitemdictQuery.eq(LabItemDict::getDelFlag, 0);
                        _labitemdictQuery.eq(LabItemDict::getEnable, 1);
                        _labitemdictQuery.orderByAsc(LabItemDict::getSeq);
                        List<LabItemDict> itemList = labItemDictMapper.selectList(_labitemdictQuery);



                        //labRptresultService.CalcTextResult(finalLabMaininfo, rptResultList);
                        /*文字结果*/
                        labRptresultCalcService.CalcTextResultV1(labMaininfo, rptResultList, itemList);
                        /*结果二次处理*/
                        //labRptresultService.CalcTransResult(finalLabMaininfo, rptResultList);
                        labRptresultCalcService.CalcTransResultV1(labMaininfo, rptResultList, itemList);
                        //计算项目处理
                        labRptresultCalcService.CalcFormulaItemResultV1(labMaininfo, rptResultList,itemList);

                        /*计算危急值*/
                        //labRptresultService.CalcItemDictCritical(finalLabMaininfo, rptResultList);
                        labRptresultCalcService.CalcItemDictCriticalV1(labMaininfo, rptResultList, itemList);

                        //labRptresultService.CalcItemDictSpecialRules(finalLabMaininfo, rptResultList);
                        /*计算结果标识特殊规则*/
                        labRptresultCalcService.CalcItemDictSpecialRulesV1(finalLabMaininfo, rptResultList);

                        /*计算完成 更新 结果*/
                        labRptresultService.saveOrUpdateBatch(rptResultList);

                        //如果finalLabMaininfo下得所有rptResultList得isResult为1，则finalLabMaininfo得isResult为1
                        this.calcIsResult(labMaininfo, rptResultList);

                        if (updateWlResultList.size() > 0) {
                            //TODO
                            //await FillRepetitionAsync(wlr.WlId, wlr.Id, wlr.AnsId, wlr.Result);
                        }
                        //转为质控
                        //TODO
                        List<String> labRptresultIds = saveOrUpdateResultList.stream().filter(a->ToolsUtils.isNotEmpty(a.getTestResult())).map(LabRptresult::getId).collect(Collectors.toList());
                        if(ToolsUtils.isNotEmpty(labRptresultIds)){
                            qcMaterialItemResultService.transToQCResultManyAsync(labRptresultIds);
                        }

                        //推送前端刷新结果
                        //TODO
                        MessageTemplate messageTemplate = new MessageTemplate();
                        messageTemplate.setLabMaininfo(labMaininfo);
                        messageTemplate.setType("RefreshResults");

                        WebSocketUtils.sendAllMessage(messageTemplate);
                    }


                }//sampleDa,prtGroup,sampleNo都不为空
                else {
                    delIntInstrResultList.addAll(intInstrResultMap.get(mainInfolist));
                }


            }//循环结束

            if (ToolsUtils.isNotEmpty(delIntInstrResultList)) {
                //删除
                List<String> ids = delIntInstrResultList.stream().map(IntInstrResult::getId).collect(Collectors.toList());
                this.removeByIds(ids);
                //插入log
                List<IntInstrResultLog> addLogList = new ArrayList<>();
                for (IntInstrResult iResult : delIntInstrResultList) {
                    IntInstrResultLog resultLog = new IntInstrResultLog();
                    BeanUtil.copyProperties(iResult, resultLog, "id");
                    resultLog.setOrgId(iResult.getOrgId());
                    resultLog.setInterfaceOrg(iResult.getOrgId());
                    addLogList.add(resultLog);
                }
                intInstrResultLogService.saveBatch(addLogList);
            }
            if (ToolsUtils.isNotEmpty(noChannelResultList)) {
                this.updateBatchById(noChannelResultList);
            }

        }

        new Thread(() -> {
            this.removeInstrResults();
        }).start();

        return Result.succ(1, "同步结果成功", null);
    }

    private void removeInstrResults() {
        //删除创建时间30天之前的数据
        LambdaQueryWrapper<IntInstrResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(IntInstrResult::getCreateTime, DateUtil.offsetDay(new Date(), -30));
        this.remove(queryWrapper);
        //删除INT_INSTR_RESULT_LOG表中30天之前的数据
        LambdaQueryWrapper<IntInstrResultLog> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.le(IntInstrResultLog::getCreateTime, DateUtil.offsetDay(new Date(), -30));
        intInstrResultLogService.remove(queryWrapper1);
    }

    @Autowired
    LabRptresultMapper labRptresultMapper;
    private void calcIsResult(LabMaininfo labMaininfo, List<LabRptresult> rptResultList) {
        LambdaQueryWrapper<LabRptresult> _labrptresultmapper = new LambdaQueryWrapper<>();
        //_labrptresultmapper.eq(LabRptresult::getMaininfoId, lmiEntry.getId());
        _labrptresultmapper.eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo());
        _labrptresultmapper.eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup());
        _labrptresultmapper.eq(LabRptresult::getSampleda, labMaininfo.getSampleda());
        _labrptresultmapper.eq(LabRptresult::getDelFlag, 0);
        List<LabRptresult> rptresultlist = labRptresultMapper.selectList(_labrptresultmapper);
        //如果labMaininfo下得所有rptresultlist得isResult为1，则finalLabMaininfo得isResult为1
        if (ToolsUtils.isNotEmpty(rptresultlist)) {
            List<LabRptresult> alarmList = rptresultlist.stream().filter(p -> ToolsUtils.isNotEmpty(p.getIsAlarm()) && p.getIsAlarm().equals(1)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(alarmList)) {
                labMaininfo.setIsAlarm(1);
             } else {
                labMaininfo.setIsAlarm(0);
            }
            List<LabRptresult> _lst = rptresultlist.stream().filter(p -> (ToolsUtils.isEmpty(p.getIsResult())||p.getIsResult() == 0)).collect(Collectors.toList());
            if (ToolsUtils.isEmpty(_lst)) {
                LabMaininfo updatInof  = new LabMaininfo();
                updatInof.setId(labMaininfo.getId());
                updatInof.setSampleda(labMaininfo.getSampleda());
                updatInof.setIsAlarm(labMaininfo.getIsAlarm());
                updatInof.setIsResult(1);
                labMaininfoService.updateById(updatInof);
            }
        }


    }


    @Autowired
    LabMainInfoServiceBakImpl labMainInfoServiceBak;
    @Override
    public Result findInstrResultNoChannelList(IntInstrResultParam param) {

        MPJLambdaWrapper<IntInstrResult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(IntInstrResult.class)
                //.eq(IntInstrResult::getDelFlag, 0)
                .and(p -> p.eq(IntInstrResult::getSampleNo, param.getSampleNo())
                        .or()
                        .eq(ToolsUtils.isNotEmpty(param.getReqNo()),IntInstrResult::getSampleNo, param.getReqNo()))
                .eq(IntInstrResult::getIsNoChannel, "Y");

        if (StringUtils.isNotBlank(param.getSampleDaStr())) {
            Timestamp startTime = Timestamp.valueOf(param.getSampleDaStr() + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(param.getSampleDaStr() + " 23:59:59");
            queryWrapper.ge(IntInstrResult::getSampleda, startTime);
            queryWrapper.le(IntInstrResult::getSampleda, endTime);
        }
        if (StringUtils.isNotBlank(param.getRptGroup())) {
            queryWrapper.eq(IntInstrResult::getRptGroup, param.getRptGroup());
        }
        List<IntInstrResult> noChannelList = intInstrResultMapper.selectList(queryWrapper);
        Map<String, Object> returnMap = new HashMap<>();
        if (ToolsUtils.isNotEmpty(noChannelList)) {
            //根据报告单元查出所有的报告项目
            MPJLambdaWrapper<LabItemDict> queryWrapper1 = new MPJLambdaWrapper<>();
            queryWrapper1.selectAll(LabItemDict.class).eq(LabItemDict::getRptGroup, param.getRptGroup()).eq(LabItemDict::getDelFlag, 0).orderByAsc(LabItemDict::getSeq);
            List<LabItemDict> labItemDicts = labItemDictMapper.selectList(queryWrapper1);
            returnMap.put("labItemDictList", labItemDicts);

        }

        returnMap.put("noChannelList", noChannelList);

        return Result.succ(1, "查询成功", returnMap);
    }

    @Override
    public Result saveBacthNoChannelResult(IntinstrReusltDto dto) {
        List<IntInstrResult> noChanneResultlList = dto.getNoChanneResultlList();
        for (IntInstrResult noChannelResult : noChanneResultlList) {
            //更新通道号数据
            LabChannel labChannel = new LabChannel();
            //labChannel.setId(intInstrResultNoChannel.getChannelId());
            labChannel.setChannelCode(noChannelResult.getItemNo());
            labChannel.setItemNo(noChannelResult.getItemDictCode());
            labChannel.setInstrCode(noChannelResult.getInstrCode());
            labChannel.setRptGroup(noChannelResult.getRptGroup());
            labChannel.setSeq("1");
            LambdaQueryWrapper<LabChannel> lambdaQueryWrappers = new LambdaQueryWrapper<>();
            lambdaQueryWrappers.eq(LabChannel::getChannelCode, noChannelResult.getItemNo())
                    .eq(LabChannel::getItemNo, noChannelResult.getItemDictCode())
                    .eq(LabChannel::getInstrCode, noChannelResult.getInstrCode())
                    .eq(LabChannel::getRptGroup, noChannelResult.getRptGroup())
                    .eq(LabChannel::getDelFlag, 0);
            boolean b = labChannelService.saveOrUpdate(labChannel, lambdaQueryWrappers);
            if (b) {
                //将所有得此数据全部更新为已处理

                LambdaUpdateWrapper<IntInstrResult> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.set(IntInstrResult::getIsNoChannel, "N").eq(IntInstrResult::getRptGroup, noChannelResult.getRptGroup()).eq(IntInstrResult::getItemNo, noChannelResult.getItemNo()).eq(IntInstrResult::getInstrCode, noChannelResult.getInstrCode()).eq(IntInstrResult::getIsNoChannel, "Y");

                int update = intInstrResultMapper.update(null, lambdaUpdateWrapper);

            }

        }

        return Result.succ(1, "处理成功", null);
    }
}
